package com.taurus.myboard.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.taurus.myboard.common.vo.Dict;
import com.taurus.myboard.common.vo.Result;
import com.taurus.myboard.entity.Job;
import com.taurus.myboard.pojo.JobVo;
import com.taurus.myboard.service.IJobService;
import com.taurus.myboard.utils.HttpClientPool;
import com.taurus.myboard.utils.ReadUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author kanten
 * @since 2023-06-16
 */
@RestController
@RequestMapping("/myboard/job")
@Slf4j
public class JobController {

    @Resource
    private IJobService jobService;
    @Resource
    private HttpClientPool httpClientPool;
    @Resource
    private ReadUtils readUtils;

    @Value("${fateflow.url}")
    private String url;

    @GetMapping("/list")
    public Result<Map<String, Object>> getList(@RequestParam(value = "role", required = false) String role,
                                                   @RequestParam(value = "partyId", required = false) String partyId,
                                                  @RequestParam(value = "status", required = false) String status,
                                                  @RequestParam(value = "note", required = false) String note,
                                                   @RequestParam(value = "pageNo") Long pageNo,
                                                   @RequestParam(value = "pageSize") Long pageSize){
        // 条件判断
        LambdaQueryWrapper<Job> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.hasLength(role), Job::getfRole, role);
        wrapper.eq(StringUtils.hasLength(partyId), Job::getfPartyId, partyId);
        wrapper.eq(StringUtils.hasLength(status), Job::getfStatus, status);
        wrapper.eq(StringUtils.hasLength(note), Job::getfDescription, note);
        wrapper.orderByDesc(Job::getfJobId);
        // 分页
        Page<Job> page = new Page(pageNo, pageSize);
        jobService.page(page, wrapper);

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("total", page.getTotal());
//        data.put("rows", page.getRecords());
        List<Job> jobs = page.getRecords();
        List<JobVo> jobVos = jobs.stream().map(result -> new JobVo(result.getfJobId(),
                result.getfRole(), result.getfPartyId(), result.getfInitiatorPartyId(),
                DateUtil.format(DateUtil.date(result.getfStartTime()).toJdkDate(), DatePattern.NORM_DATETIME_PATTERN),
                DateUtil.format(DateUtil.date(result.getfEndTime()).toJdkDate(), DatePattern.NORM_DATETIME_PATTERN),
                DateUtil.secondToTime(result.getfElapsed()/1000), "success"))
                .collect(Collectors.toList());
        data.put("rows", jobVos);
//        log.info("data: " + data);
        return Result.success(data);
    }

    @GetMapping("/jobList")
    public Result<Map<String, Object>> getJobList(@RequestParam(value = "role", required = false) String role,
                                                  @RequestParam(value = "partyId", required = false) String partyId,
                                                  @RequestParam(value = "status", required = false) String status,
                                                  @RequestParam(value = "note", required = false) String note,
                                                  @RequestParam(value = "pageNo") Long pageNo,
                                                  @RequestParam(value = "pageSize") Long pageSize){
        Map<String, Object> data = jobService.getJobList(role, partyId, status, note, pageNo, pageSize);
        return Result.success(data);
    }

    @GetMapping("/submit")
    public Result submit(){
        JSONObject job_runtime_conf = buildJobRuntimeCnf();
        JSONObject job_dsl = buildJobDsl();
        JSONObject jobRequest = new JSONObject();
        Map<String, Object> jobParams = new HashMap<>();
        jobParams.put(Dict.JOB_RUNTIME_CONF, job_runtime_conf);
        jobParams.put(Dict.JOB_DSL, job_dsl);
        String rst = httpClientPool.post(url + Dict.URL_SUBMIT_JOB, JSON.toJSONString(jobParams));
        return Result.success(rst);
    }

    @PostMapping("/submitJob")
    public Result submitJob(@RequestParam("file") MultipartFile[] files) throws IOException {
        MultipartFile dslFile = files[0];
        log.info("接收到的文件数据为：" + dslFile);
        if (dslFile.isEmpty()) return Result.fail("上传文件为空");
        MultipartFile cnfFile = files[1];
        log.info("接收到的文件数据为：" + cnfFile);
        if (cnfFile.isEmpty()) return Result.fail("上传文件为空");

        FileUtils.writeByteArrayToFile(new File(dslFile.getOriginalFilename()), dslFile.getBytes());
        JSONObject job_dsl = getJoFromMpf(dslFile);

        FileUtils.writeByteArrayToFile(new File(cnfFile.getOriginalFilename()), cnfFile.getBytes());
        JSONObject job_runtime_conf = getJoFromMpf(cnfFile);

        Map<String, Object> jobParams = new HashMap<>();
        jobParams.put(Dict.JOB_RUNTIME_CONF, job_runtime_conf);
        jobParams.put(Dict.JOB_DSL, job_dsl);
        String rst = httpClientPool.post(url + Dict.URL_SUBMIT_JOB, JSON.toJSONString(jobParams));
        return Result.success(rst);
    }

    private JSONObject getJoFromMpf(MultipartFile multipartFile) {
        String jsonName = multipartFile.getOriginalFilename(); //获取JSON类型的文件名
        String jsonContext = readUtils.ReadFile(jsonName);  //输出的数据是{}花括号包裹的　　
        JSONObject jsonObject = JSONObject.parseObject(jsonContext);
        return jsonObject;
    }

    private JSONObject buildJobDsl() {
        JSONObject jobDsl = new JSONObject();
        JSONObject components = buildComponents();
        jobDsl.put("components", components);
        return jobDsl;
    }

    private JSONObject buildComponents() {
        JSONObject components = new JSONObject();
        // reader_0
        JSONObject reader_0 = buildReader0();
        components.put("reader_0", reader_0);
        // data_transform_0
        JSONObject data_transform_0 = buildDataTransform();
        components.put("data_transform_0", data_transform_0);
        // homo_data_split_0
        JSONObject homo_data_split_0 = buildHomeDataSplit();
        components.put("homo_data_split_0", homo_data_split_0);
        return components;
    }

    private JSONObject buildHomeDataSplit() {
        JSONObject homeDataSplit = new JSONObject();
        // module
        homeDataSplit.put("module", "myDataSplit");
        // input
        JSONArray arData1 = new JSONArray();
        arData1.add("data_transform_0.data");
        JSONObject data1 =  new JSONObject();
        data1.put("data", arData1);
        JSONObject input =  new JSONObject();
        input.put("data", data1);
        homeDataSplit.put("input", input);
        // output
        JSONArray arData2 = new JSONArray();
        arData2.add("train_data");
        arData2.add("validate_data");
        arData2.add("test_data");
        JSONObject output = new JSONObject();
        output.put("data", arData2);
        homeDataSplit.put("output", output);
        return homeDataSplit;
    }

    private JSONObject buildDataTransform() {
        JSONObject dataTransform = new JSONObject();
        dataTransform.put("module", "DataTransform");
        JSONObject input = buildInput();
        dataTransform.put("input", input);
        JSONObject output = buildOutput();
        dataTransform.put("output", output);
        return dataTransform;
    }

    private JSONObject buildReader0() {
        JSONObject reader0 = new JSONObject();
        // module
        reader0.put("module", "Reader");
        // output
        JSONObject output = new JSONObject();
        JSONArray arData = new JSONArray();
        arData.add("data");
        output.put("data", arData);
        reader0.put("output", output);
        return reader0;
    }

    private JSONObject buildOutput() {
//        "output": {
//            "data": [
//            "data"
//                    ],
//            "model": [
//            "model"
//                    ]
//        }
        JSONObject output = new JSONObject();
        JSONArray arData = new JSONArray();
        arData.add("data");
        JSONArray arModel = new JSONArray();
        arModel.add("model");
        output.put("data", arData);
        output.put("model", arModel);
        return output;
    }

    private JSONObject buildInput() {
//        "data": {
//            "data": [
//            "reader_0.data"
//                        ]
//        }
        JSONArray arData = new JSONArray();
        arData.add("reader_0.data");
        JSONObject data = new JSONObject();
        data.put("data", arData);
        JSONObject input = new JSONObject();
        input.put("data", data);
        return input;
    }

    private JSONObject buildJobRuntimeCnf() {
        JSONObject jobRuntimeCnf = new JSONObject();
        jobRuntimeCnf.put("dsl_version", 2);
        // initiator
        JSONObject initiator = buildInitiator();
        jobRuntimeCnf.put("initiator", initiator);
        // role
        JSONObject role = buildRole();
        jobRuntimeCnf.put("role", role);
        // component_parameters
        JSONObject component_parameters = buildComponentParameters();
        jobRuntimeCnf.put("component_parameters", component_parameters);
        return jobRuntimeCnf;
    }

    private JSONObject buildComponentParameters() {
        JSONObject component_parameters = new JSONObject();
        // common
        JSONObject common = new JSONObject();
        // --homo_data_split_0
        JSONObject homo_data_split_0 = new JSONObject();
        homo_data_split_0.put("test_size", 0.3);
        homo_data_split_0.put("validate_size", 0.2);
        homo_data_split_0.put("stratified", true);
        common.put("homo_data_split_0", homo_data_split_0);
        component_parameters.put("common", common);
        // role
        JSONObject role = new JSONObject();
        // --host
        JSONObject host = buildRoleInfo("breast_homo_host", "", "", "");
        role.put("host", host);
        // --guest
        JSONObject guest = buildRoleInfo("breast_homo_guest", "y", "int", "dense");
        role.put("guest", guest);
        component_parameters.put("role", role);
        return component_parameters;
    }

    private JSONObject buildRoleInfo(String table_name, String label_name, String label_type, String output_format) {
        JSONObject roleInfo = new JSONObject();
        // 0
        JSONObject role_0 = new JSONObject();
        // --reader_0
        JSONObject reader_0 = new JSONObject();
        // --|--table
        JSONObject table = new JSONObject();
        table.put("name", table_name);
        table.put("namespace", "experiment");
        reader_0.put("table", table);
        role_0.put("reader_0", reader_0);
        // --data_transform_0
        JSONObject data_transform_0 = new JSONObject();
        data_transform_0.put("with_label", true);
        if (StringUtils.hasLength(label_name)) data_transform_0.put("label_name", label_name);
        if (StringUtils.hasLength(label_type)) data_transform_0.put("label_type", label_type);
        if (StringUtils.hasLength(output_format)) data_transform_0.put("output_format", output_format);
        role_0.put("data_transform_0", data_transform_0);
        roleInfo.put("0", role_0);
        return roleInfo;
    }

    private JSONObject buildRole() {
        JSONObject role = new JSONObject();
        JSONArray arHost = new JSONArray();
        arHost.add(10000);
        role.put("host", arHost);
        JSONArray arGuest = new JSONArray();
        arGuest.add(10000);
        role.put("guest", arGuest);
        return role;
    }

    private JSONObject buildInitiator() {
        JSONObject initiator = new JSONObject();
        initiator.put("role", "guest");
        initiator.put("party_id", 10000);
        return initiator;
    }
}
